package com.dubbo.framework.protocol.dubbo;

import com.dubbo.framework.Invocation;
import com.dubbo.framework.register.RemoteMapRegister;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * @author by Mr. Li 2021/4/30 13:55
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<Invocation> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Invocation invocation) throws Exception {
        log.info("netty server handler running ..");

        // 拉取 zk 配置信息
        final Class clazz = RemoteMapRegister.getMetaInfo(invocation.getInterfaceName());
        final Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        final Object result = method.invoke(clazz.newInstance(), invocation.getParams());

        log.info("netty server success,message is {} , write byte to client", result);

        channelHandlerContext.writeAndFlush(result);
    }
}
